from asyncio import exceptions

from elasticsearch import Elasticsearch, helpers
import json

# 初始化Elasticsearch客户端
es = Elasticsearch([{'host': '10.206.60.14', 'port': 9200}])

# 索引名称
index_name = "case_index_1"

# 查询所有文档
query = {
    "query": {
        "match_all": {}
    }
}

def create_index(index_name):
    settings = {
        "settings": {
            "analysis": {
                "analyzer": {
                    "ik_max_word_analyzer": {
                        "type": "custom",
                        "tokenizer": "ik_max_word"
                    }
                }
            }
        },
        "mappings": {
            "properties": {
                "item_name": {
                    "type": "text",
                    "analyzer": "ik_max_word_analyzer",
                    "search_analyzer": "ik_max_word_analyzer"
                },
                "item_id": {"type": "keyword"},
                "base_info": {
                    "type": "object",
                    "properties": {
                        "id": {"type": "keyword"},
                        "name": {"type": "text"},
                        "agent_name": {"type": "text"},
                        "org_property": {"type": "text"},
                        "org_name": {"type": "text"},
                        "service_object_name": {"type": "text"},
                        "type": {"type": "text"},
                        "office_hour": {"type": "text"},
                        "address": {"type": "text"},
                        "id_public": {"type": "keyword"},
                        "handle_mode": {"type": "text"},
                        "is_agencyorgan": {"type": "keyword"},
                        "org_name_item": {"type": "text"},
                        "auth_level": {"type": "text"},
                        "law_time": {"type": "text"},
                        "law_time_unit": {"type": "text"},
                        "agree_time": {"type": "text"},
                        "is_charge": {"type": "keyword"},
                        "corss_scope": {"type": "text"},
                        "handle_form": {"type": "text"},
                        "pay_online": {"type": "keyword"},
                        "is_delivery": {"type": "keyword"},
                        "is_in_hall": {"type": "keyword"},
                        "item_id": {"type": "keyword"},
                        "assort": {"type": "text"},
                        "power_source": {"type": "text"},
                        "authority_division": {"type": "text"},
                        "conduct_depth": {"type": "text"},
                        "apply_times": {"type": "text"},
                        "result_type": {"type": "text"},
                        "service_mode": {"type": "text"},
                        "is_reserve": {"type": "keyword"},
                        "code": {"type": "keyword"},
                        "is_online": {"type": "keyword"}
                    }
                },
                "common_questions": {
                    "type": "nested",
                    "properties": {
                        "id": {"type": "keyword"},
                        "question": {"type": "text"},
                        "answer": {"type": "text"}
                    }
                },
                "legal_basis": {
                    "type": "nested",
                    "properties": {
                        "id": {"type": "keyword"},
                        "office": {"type": "text"},
                        "law_number": {"type": "text"},
                        "content": {"type": "text"},
                        "file_url": {"type": "text"}
                    }
                },
                "materials": {
                    "type": "nested",
                    "properties": {
                        "id": {"type": "keyword"},
                        "name": {"type": "text"},
                        "accept_standard": {"type": "text"},
                        "document_format": {"type": "text"},
                        "material_type": {"type": "text"},
                        "must": {"type": "keyword"},
                        "paper_standard": {"type": "text"},
                        "what": {"type": "text"},
                        "original": {"type": "text"},
                        "sample": {"type": "keyword"},
                        "sample_name": {"type": "text"},
                        "blank": {"type": "keyword"},
                        "blank_name": {"type": "text"}
                    }
                },
                "process": {
                    "type": "nested",
                    "properties": {
                        "id": {"type": "keyword"},
                        "name": {"type": "text"},
                        "time_limit": {"type": "text"},
                        "remark": {"type": "text"},
                        "user_name": {"type": "text"}
                    }
                },
                "charge": {
                    "type": "nested",
                    "properties": {
                        "id": {"type": "keyword"},
                        "name": {"type": "text"},
                        "basis": {"type": "text"},
                        "standard": {"type": "text"}
                    }
                },
                "complain": {
                    "type": "nested",
                    "properties": {
                        "id": {"type": "keyword"},
                        "name": {"type": "text"},
                        "type": {"type": "text"},
                        "phone": {"type": "text"},
                        "region_code": {"type": "text"},
                        "address": {"type": "text"},
                        "remark": {"type": "text"}
                    }
                },
                "condition": {
                    "type": "nested",
                    "properties": {
                        "id": {"type": "keyword"},
                        "name": {"type": "text"},
                        "code": {"type": "keyword"},
                        "item_id": {"type": "keyword"},
                        "item_name": {"type": "text"}
                    }
                }
            }
        }
    }
    try:
        if not es.indices.exists(index=index_name):
            es.indices.create(index=index_name, body=settings)
            print(f"Index {index_name} created successfully.")
        else:
            print(f"Index {index_name} already exists.")
    except exceptions.RequestError as e:
        print(f"An error occurred: {e}")


def delete_index(index):
    if es.indices.exists(index=index):
        response = es.indices.delete(index=index)
        print("Index deleted:", response)
    else:
        print("Index does not exist.")



# 导出数据到JSON文件
def export_data(es, index_name, query, file_name):
    es_docs = helpers.scan(es, query=query, index=index_name)
    with open(file_name, 'w', encoding='utf-8') as f:
        for doc in es_docs:
            json.dump(doc["_source"], f, ensure_ascii=False)
            f.write("\n")


# 导入数据到Elasticsearch
def import_data(es, index_name, file_name):
    with open(file_name, 'r', encoding='utf-8') as f:
        actions = []
        for line in f:
            doc = json.loads(line)
            action = {
                "_index": index_name,
                "_source": doc
            }
            actions.append(action)
        helpers.bulk(es, actions)

# delete_index(index_name)
# create_index(index_name)
export_data(es, index_name, query, "case_index.json")
# import_data(es, index_name, "dy_case_export.json")
print("Data imported successfully!")
